package com.zcsy.manage.web.property;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.CommonConfig;
import com.zcsy.manage.model.base.CommonImg;
import com.zcsy.manage.model.base.OwnerHouse;
import com.zcsy.manage.model.complain.ComplaintsReply;
import com.zcsy.manage.model.property.RepairInfo;
import com.zcsy.manage.model.property.RepairReply;
import com.zcsy.manage.model.system.Menu;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.ICommonConfigService;
import com.zcsy.manage.service.base.ICommonImgService;
import com.zcsy.manage.service.base.IOwnerHouseService;
import com.zcsy.manage.service.mall.IIntegralConfigService;
import com.zcsy.manage.service.mall.IIntegralRecordService;
import com.zcsy.manage.service.property.IRepairInfoService;
import com.zcsy.manage.service.property.IRepairReplyService;
import com.zcsy.manage.service.system.IMenuService;

@Controller
@RequestMapping(value = "propertyRepair")
public class PropertyRepairController {

    @Autowired
    private IRepairInfoService repairInfoService;

    @Autowired
    private IRepairReplyService repairReplyService;

    @Autowired
    private ICommonImgService commonImgService;

    @Autowired
    private IOwnerHouseService ownerHouseService;
    
    @Autowired
    private ICommonConfigService commonConfigService;
    
    @Autowired
    private IIntegralRecordService integralRecordService;
    
    @Autowired
    private IIntegralConfigService IntegralConfigService;
    
    @Autowired
    private IMenuService menuService;
    
    @Autowired
    private ICellInfoService cellInfoService;

    private final static int LEVEL_five   = 5;  //默认危害程度
    private final static int SIZE         = 4;  //分页大小
    private final static int propertyType = 1;  //物业回复
    private final static int ownerType    = 2;  //业主回复

    /**
     * @description 物业保修编辑页面跳转
     * @return 编辑页面路径 String
     * @author chenxin
     * @date 2016年8月3日下午2:39:45
     */
    @RequestMapping(value = "goToEditPage", method = RequestMethod.GET)
    public String goToEditPage(Model model, HttpServletRequest req) {

        try {
            // 获取到当前用户登陆时默认的小区id
            String cellId = ((CellInfo) req.getSession().getAttribute(RequestConstants.OWNER_CELL_INFO)).getId();
            // 获取当前登陆的用户的信息
            User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

            String ownerId = user.getId();
            OwnerHouse ownerHouse = new OwnerHouse();
            List<CellHouse> cellHouseList = ownerHouseService.getCurrentCellHouse(ownerId, cellId);

            if (!StringUtils.isEmpty(ownerId)) {
                ownerHouse.setOwnerId(ownerId);
            }
            
            checkingPropertyRightByCellId(req,model);
            checkingCarRightByCellId(req,model); 
            
            model.addAttribute("cellHouseList", cellHouseList);
            model.addAttribute("cellId", cellId);
            model.addAttribute("level", LEVEL_five);

        } catch (Exception e) {
        }
        return "property/repairinfo/repairInfoEdit";
    }

    /**
     * @description 保存报修信息
     * @param title 标题
     * @param houseId 房屋id
     * @param contactor 联系人
     * @param contactorPhone 联系电话
     * @param level 危害程度
     * @param content 内容
     * @param imgArr 照片名数组
     * @author chenxin
     * @date 2016年8月10日上午10:24:32
     */
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdate(Model model, String title, String houseId, String contactor, String contactorPhone,Integer type,
            Integer level, String content, @RequestParam(value = "imgArr[]" ,required = false) String[] imgArr, HttpServletRequest req) {
        
        RequestJson result = new RequestJson();

        try {
            User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            RepairInfo repairInfo = new RepairInfo();

            repairInfo.setId(UniqueNumberUtils.get18UniqueNumber());
            repairInfo.setCreateTime(DateUtils.getDate());
            repairInfo.setOwnerId(user.getId());
            repairInfo.setTitle(title);
            repairInfo.setContactorPhone(contactorPhone);
            repairInfo.setContactor(contactor);
            repairInfo.setContent(content);
            repairInfo.setLevel(level);
            repairInfo.setHouseId(houseId);
            repairInfo.setState(Constants.STATE_DISABLED);
            repairInfo.setType(type);
            
            repairInfoService.insert(repairInfo);
            
            if (imgArr != null) {
                List<CommonImg> imgs = commonImgService.selectImgsByObjIdAndObjType(repairInfo.getId(),
                        Constants.IMG_REPAIRE);

                if (CollectionUtils.isNotEmpty(imgs)) {
                    for (CommonImg commonImg : imgs) {
                        commonImgService.deleteById(commonImg.getId());
                    }
                }

                CommonImg commonImg = new CommonImg();
                for (String item : imgArr) {
                    commonImg.setId(UniqueNumberUtils.get18UniqueNumber());
                    commonImg.setUrl(item);
                    commonImg.setObjId(repairInfo.getId());
                    commonImg.setObjType(Constants.IMG_REPAIRE);
                    commonImgService.insert(commonImg);
                }
            }
            /**************************************用户单次投诉、建议或者报修，获得积分10************************************/
            //用户Id
            String userId = user.getId();
            String userAccount = user.getLoginname();
            //根据唯一标识name获取“每日积分上限”的小区配置信息
            CommonConfig commonConfig = commonConfigService.getByName("mall_integral_config");
            //用户当天可加积分之和的上限
            Integer maxValuePerDay = commonConfigService.getIntegralMaxValueOfCell("mall_integral_config");
            //根据唯一标识name获取"投诉建议或报修"可获得的积分值
            Integer integralOfcomplaintAndRepair = IntegralConfigService.getIntegralValue("propertyRepair");
            //获取用户当天积分变动之和
            Integer soFarIntegralSum = integralRecordService.getIntegralOfToday(userId);
           
            // 验证小区配置的积分上限值不为空以及值得有效性
            if (commonConfig != null && maxValuePerDay.toString().matches("[0-9]+")) {
                // 当日积分上限 > 投诉建议获得积分 && 当天的积分变动值之和 <（积分上限-投诉建议获得积分）
                if (maxValuePerDay > integralOfcomplaintAndRepair && soFarIntegralSum < (maxValuePerDay - integralOfcomplaintAndRepair)) {
                    // 插入积分变更信息
                    integralRecordService.changeIntegralMethod(userAccount, "propertyRepair");
                    result.setMsg("投诉建议成功获得10个积分！");
                }
                // 用户当日变动的积值之和 == 积分上限
                if(soFarIntegralSum == maxValuePerDay) {
                    result.setMsg("已达今日累加积分上限");
                }
                // 用户当日变动积分值之和 < 积分上限 && 用户当日变动积分值之和 >(积分上限-投诉建议成功获得的积分)
                if(soFarIntegralSum < maxValuePerDay && soFarIntegralSum > (maxValuePerDay - integralOfcomplaintAndRepair)) {
                    // 插入积分变更信息
                    integralRecordService.changeIntegralWhenToMaxValuePerDay(userAccount, "propertyRepair",maxValuePerDay - soFarIntegralSum);
                    result.setMsg("投诉建议成功获得10个积分！，但是已达今日累积积分上限！");
                }
            }
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作异常！");
        }
        return result;
    }

    /**
     * @description 物业投诉的列表
     * @return 返回列表页面 String
     * @author chenxin
     * @date 2016年8月3日下午2:39:14
     */
    @RequestMapping(value = "infoList", method = RequestMethod.GET)
    public String infoList(Model model, Integer pNo, HttpServletRequest req) {

        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }
        
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, SIZE);
        List<RepairInfo> repairInfos = repairInfoService.getAll(user.getId());
        PageInfo<RepairInfo> pageInfo = new PageInfo<RepairInfo>(repairInfos);
        
        checkingPropertyRightByCellId(req,model);
        checkingCarRightByCellId(req,model); 
        
        model.addAttribute("repairInfos", pageInfo);
        model.addAttribute("currentPage", pNo);
        return "property/repairinfo/repairInfoList";
    }

    /**
     * @description 显示物业保修详情页
     * @param id  投诉单号
     * @return String 返回详情路径
     * @author chenxin
     * @date 2016年8月3日下午4:12:39
     */
    @RequestMapping(value = "showDetails", method = RequestMethod.GET)
    public String showDetails(Integer pNo, Model model, String id) {
        try {
            if (pNo == null) {
                pNo = Constants.PAGE_NO;
            }
            RepairInfo repairInfo = repairInfoService.selectByPrimaryKey(id);

            RepairReply repairReply = new RepairReply();
            repairReply.setRepairId(id);
            //平台的回复
            repairReply.setReplyType(propertyType);
            List<RepairReply> platformReply = repairReplyService.selectByKeyword(repairReply);
            
            //业主回复
            repairReply.setReplyType(ownerType);
            List<RepairReply> ownerReply = repairReplyService.selectByKeyword(repairReply);
            
            // 获取业主投诉图
            List<CommonImg> imgs = commonImgService.selectImgsByObjIdAndObjType(id, Constants.IMG_REPAIRE);
            model.addAttribute("imgs", imgs);
            model.addAttribute("repairInfo", repairInfo);
            model.addAttribute("platformReply", platformReply);
            model.addAttribute("ownerReply", ownerReply);

        } catch (Exception e) {
        }
        return "property/repairinfo/repairInfoDetail";
    }
    
    /**
     * @description 保存业主的报修评论
     * @param replys
     * @author chenxin
     * @date 2016年8月4日下午6:08:45
     */
    @RequestMapping(value = "saveReply", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveReply(Model model, RepairReply replys,HttpServletRequest req){
        RequestJson result = new RequestJson();
        try {
            User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            
            replys.setId(UniqueNumberUtils.get18UniqueNumber());
            replys.setReplyTime(DateUtils.getDate());
            replys.setReplyType(ownerType);
            replys.setReplyAccount(user.getUsername());
            
            repairReplyService.insert(replys);
            
            /**************************************用户单次评论获得积分5************************************/
            //用户Id
            String userId = user.getId();
            String userAccount = user.getLoginname();
            //根据唯一标识name获取“每日积分上限”的小区配置信息
            CommonConfig commonConfig = commonConfigService.getByName("mall_integral_config");
            //用户当天可加积分之和的上限
            Integer maxValuePerDay = commonConfigService.getIntegralMaxValueOfCell("mall_integral_config");
            //根据唯一标识name获取"投诉建议或报修"可获得的积分值
            Integer integralOfcomplaintAndRepair = IntegralConfigService.getIntegralValue("common");
            //获取用户当天积分变动之和
            Integer soFarIntegralSum = integralRecordService.getIntegralOfToday(userId);
           
            // 验证小区配置的积分上限值不为空以及值得有效性
            if (commonConfig != null && maxValuePerDay.toString().matches("[0-9]+")) {
                // 当日积分上限 > 投诉建议获得积分 && 当天的积分变动值之和 <（积分上限-投诉建议获得积分）
                if (maxValuePerDay > integralOfcomplaintAndRepair && soFarIntegralSum < (maxValuePerDay - integralOfcomplaintAndRepair)) {
                    //插入积分变更信息
                    integralRecordService.changeIntegralMethod(userAccount, "common");
                    result.setSuccess(true);
                    result.setMsg("评价成功获得5个积分！");
                }
                // 用户当日变动的积值之和 == 积分上限
                if(soFarIntegralSum == maxValuePerDay) {
                    result.setMsg("已达今日累加积分上限");
                }
                // 用户当日变动积分值之和 < 积分上限 && 用户当日变动积分值之和 >(积分上限-投诉建议成功获得的积分)
                if(soFarIntegralSum < maxValuePerDay && soFarIntegralSum > (maxValuePerDay - integralOfcomplaintAndRepair)) {
                    // 插入积分变更信息
                    integralRecordService.changeIntegralWhenToMaxValuePerDay(userAccount, "common",maxValuePerDay - soFarIntegralSum);
                    result.setMsg("评价成功获得5个积分！，但是已达今日累积积分上限！");
                }
            }
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作异常！");
        }
        return result;
    }
    
    /**
     * @Description: 删除照片
     * @param imageId 照片id
     * @author huangls 1449700087@qq.com
     * @date 2016年8月16日
     */
    @RequestMapping(value = "deleteImage", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteImage(Model model, String imageId, HttpServletRequest req) {

        RequestJson result = new RequestJson();

        try {
        	
        	if(imageId != null) {
        		commonImgService.deleteById(imageId);
        		result.setSuccess(true);
                result.setMsg("操作成功！");
        	}
            
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作异常！");
        }
        return result;
    }
    
    /**
     * @description 检验此小区是否具有缴纳停车费的权限
     * @param cellId 小区id
     * @author chenxin
     * @date 2016年8月31日下午6:54:39
     */
    public void checkingCarRightByCellId(HttpServletRequest request, Model model) {
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        CellInfo cellInfo = user.getCurrentCell();
        String cellId = cellInfo.getId();
        
        List<String> list = cellInfoService.getMenusByCellId(cellId, Constants.SYSTEM_OWNER);
        
        for (String item : list) {
            Menu menu = menuService.getMenuById(item);
            String value = menu.getValue();
            if(StringUtils.equals(value, "owner.car")) {
                model.addAttribute("displayCar", Constants.STATE_ENABLED);
            }  
        }
    }
    
    /**
     * @description 检验此小区是否具有缴纳物业费的权限     
     * @param cellId 小区id                 
     * @author chenxin
     * @date 2016年8月31日下午6:54:39
     */
    public void checkingPropertyRightByCellId(HttpServletRequest request, Model model) {
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        CellInfo cellInfo = user.getCurrentCell();
        String cellId = cellInfo.getId(); 
        
        List<String> list = cellInfoService.getMenusByCellId(cellId, Constants.SYSTEM_OWNER);
        
        for (String item : list) {
            Menu menu = menuService.getMenuById(item);
            String value = menu.getValue();
            if (StringUtils.equals(value, "owner.propertyFee")) {
                model.addAttribute("displayFeeBill", Constants.STATE_ENABLED);
            }
        }
    }
}
